import json

from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse, JsonResponse
from django.core import serializers
from rest_framework.response import Response
from rest_framework.views import APIView

from rank.models import Score


class Rank(APIView):

    def get(self, request):
        client = request.GET.get("client")
        score = Score.objects.filter(client=client).first()
        if not score:
            resp_data = {"errmsg": "用户不存在"}
            return Response(resp_data)
        data = {}
        scores = serializers.serialize("json", Score.objects.all().order_by('fraction'))
        data["data"] = json.loads(scores)
        return JsonResponse(data, safe=False)

    def post(self, request):
        data = json.loads(request.body.decode())
        client = data.get('client')
        fraction = data.get('fraction')
        if not all([client, fraction]):
            resp_data = {"errmsg": "参数错误"}
            return Response(resp_data)
        try:
            fraction = int(fraction)
        except Exception as e:
            resp_data = {"errmsg": "分数必须为整数"}
            return Response(resp_data)
        if fraction < 1 or fraction > 10000:
            resp_data = {"errmsg": "分数不能大于10000或小于1"}
            return Response(resp_data)
        score = Score()
        score.client = client
        score.fraction = fraction
        score.save()

        return HttpResponse(json.dumps(data), content_type='application/json')